
var forceEndTurn = false;
function disableButtons() {
	var b = document.getElementById('gotobuybtn');
	b.disabled = true;
	b = document.getElementById('playtreasuresbtn');
	b.disabled = true;
	b = document.getElementById('endturnbtn');
	b.disabled = true;
	b = document.getElementById('undobtn');
	b.disabled = true;
}

function updateChatLines(data) {
	if (data.modifications == false)
		return;
	var last_chat_id = document.getElementById('last_chat_id').title;
	var chatwindow = document.getElementById('chatwindow');
	if (!chatwindow)
		return;
	var innerHtml = chatwindow.innerHTML;
	var alen = data.chat.lines.length;
	var last_id = last_chat_id;
	for ( var i=0, len=alen; i<len; ++i ){
		if (parseInt(data.chat.lines[i].id) > last_id) {
			innerHtml += "<b>" + data.chat.lines[i].name +":</b> "+data.chat.lines[i].line+"<br>";
			last_id = parseInt(data.chat.lines[i].id);
		}
	}
	if (last_chat_id != last_id)
		ChatAlertMe();
	document.getElementById('last_chat_id').title = last_id;
	chatwindow.innerHTML = innerHtml;
	$('#chatwindow').prop("scrollTop", $("#chatwindow").prop('scrollHeight'));
}

function clearInput() {
	var sec_options = document.getElementById('sec_options');
	sec_options.innerHTML = "<br>";
}

function setData(data) {
    if (!data)
		return;
	forceEndTurn = false;
	var f_uniqueid = document.getElementById('uniqueid');
	var current_uniqueid = f_uniqueid.title;
	var new_uniqueid = data.uniqueid;
        
	if (current_uniqueid != new_uniqueid) {
		f_uniqueid.title = new_uniqueid;
		f_uniqueid.innerHTML = new_uniqueid;
		var player = new Player();
		player.parseresults(data);
                
		var resources = new Resources();
		resources.parseresults(data);
			
		var board = new Board();
		board.parseresults(data);
                
	}
        
	var trailer = new Trailer();
	trailer.update(data);
}

function refresh() {
	ajaxSendHelper('getGameData',"");
}

function playAction(card) {
	var sec_choises = document.getElementById('sec_choises');
	disableButtons();
	ajaxSendHelper('action', "&card="+card);
}

function playSingleInput(i) {
	var sec_options = document.getElementById('sec_options');
	sec_options.style.display = 'none';
	var rid = document.getElementById('roomid');
	var params = "&roomid="+roomid;
	
	var x = document.getElementById(i);
	for ( var j=0; j<i; ++j ){
		params += "&"+j+"=off";
	}
	params += "&"+i+"="+x.value;
	
	ajaxSendHelper('input', params);
}

function playInput(alen) {
	var sec_options = document.getElementById('sec_options');
	sec_options.style.display = 'none';
	
	var rid = document.getElementById('roomid');
	var roomid = rid.innerHTML
	var params = "&roomid="+roomid;
	choosen = 0;
	for ( var i=0, len=alen; i<len; ++i ){
		var x = document.getElementById(i);
		if (x.checked) {
			choosen += 1;
			params += "&"+i+"="+x.value;
		}
		else {
			params += "&"+i+"=off";
		}
	}
	var min = document.getElementById("mincheckbox").value;
	var max = document.getElementById("maxcheckbox").value;
	if ((choosen >= min) && (choosen <= max || max == -1)) {
		var sec_options = document.getElementById('sec_options');
		clearInput();
		ajaxSendHelper('input', params);
	}
	else {
		alert("Please choose the correct number of options")
		sec_options.style.display = 'inline';
	}
}

function trim (str)
{
     return str.replace (/^\s+|\s+$/g, '');
}


function addChatLine() {
	chatForm = document.getElementById('chatfrm');
	line =  chatForm.line.value
	chatForm.line.value = "";
	if (trim(line) != '')
	{
		line = encodeURIComponent(line);
		ajaxSendHelper('addChatLine',"&line="+line);
	}
}

function playCoinTokens() {
	disableButtons();
	ajaxSendHelper('playCoinTokens',"");
}

function goToBuy() {
	var sec_choises = document.getElementById('sec_choises');
	disableButtons();
	ajaxSendHelper('buyPhase',"");
}

function goToBuyAndPlayAllTreasures() {
	var sec_choises = document.getElementById('sec_choises');
	disableButtons();
	ajaxSendHelper('buyPhaseAndPlayAllTreasures',"");
}

function undo() {
	ajaxSendHelper('undo',"");
}

function playPayment(card) {
	var sec_choises = document.getElementById('sec_choises');
	disableButtons();
	var sec_buycards = document.getElementById('sec_buycards');
	sec_buycards.innerHTML = "";
	ajaxSendHelper('payment', "&card="+card);
}

function playBuy(card) {
	var sec_choises = document.getElementById('sec_choises');
	disableButtons();
	var sec_buycards = document.getElementById('sec_buycards');
	sec_buycards.innerHTML = "";
	ajaxSendHelper('buy', "&card="+card);
}

function endTurn() {
	
	var my_phase = document.getElementById('my_phase').textContent;
	var my_coins = document.getElementById('my_coins').textContent;
	my_coins = parseInt(my_coins.substring(0, my_coins.length-1));
	var my_buys = parseInt(document.getElementById('my_buys').textContent);
	var my_actions = parseInt(document.getElementById('my_actions').textContent);
	
	var areltEndTurn = false;
	if (forceEndTurn == false && my_phase == 'Action' && my_actions > 0) {
		areltEndTurn = true;
	}
	if (forceEndTurn == false && my_phase == 'Buy' && my_buys > 0) {
		areltEndTurn = true;
	}
	
	if (areltEndTurn) {
		forceEndTurn = true;
		document.getElementById('endturnbtn').value = "End Turn?";
		return;
	}
	forceEndTurn == false;
	
	var sec_choises = document.getElementById('sec_choises');
	disableButtons();
	var sec_buycards = document.getElementById('sec_buycards');
	sec_buycards.innerHTML = "";
	var sec_options = document.getElementById('sec_options');
	clearInput();
	ajaxSendHelper('endturn',"");
	
}

function displayOrderTable() {
	var table = document.getElementById('ordertbl');
	var tableDnD = new TableDnD();
	tableDnD.init(table);
}

function orderTableSubmit() {
	var params = ""
	var counter = 0
	var lis = document.getElementById("sortable");
	
	for(var i = 0; i < lis.children.length; i++) {
		if (lis.children[i].innerText)
			params += "&"+counter+"="+lis.children[i].innerText;	
		else
			params += "&"+counter+"="+lis.children[i].textContent;	
		counter++;
	}
	ajaxSendHelper('input',params);
}

function pageScroll() {
    //window.scrollTo(0,document['body'].offsetHeight);
}

function ajaxSendHelper(cmd, extradata) {
	
	$.ajax({
		url: "index.php",
		data: "cmd="+cmd+""+extradata,
		type: "POST",
		dataType: "json",
		success: function(data) {
			setData(data);
			pageScroll();
		},
        error: function (xhr, ajaxOptions, thrownError){
			if (xhr.responseText) {
				alert("Error on server.");
			}
			var sec_debug = document.getElementById('sec_debug');
			
            sec_debug.innerHTML = xhr.responseText;
        }   
	});
}

function num2html(name, num) {
	var card = allCardsArray[name];
	var htmldata = ""
	htmldata += card2html(card, "", "", false);
	htmldata += "<font size='1'>"+num+" </font><br>";
	return htmldata;
}

function cardsNum2html(name,num, tooltip, isPrintNum) {
	var htmldata = ""
	if (tooltip)
		htmldata += "<a href='#' title='"+tooltip+"' onclick='return false'> <b>"+name+":</b> </a>";
	else
		htmldata += "<b>"+name+":</b> ";
	
	if (isPrintNum) {
		htmldata += num+" cards <br>";
	}
	else if (num > 0) {
		htmldata += "<hr size=15 width="+num*2+" align='left' noshade/>"	
	}
	else {
		htmldata+="<br />"
	}
	return htmldata;
}

function cards2html(name, arr, tooltip, phase, markCards, withImages) {
	var htmldata = "";
	htmldata += "<table><tr><td>";
	if (tooltip) 
		htmldata += "<a href='#' title='"+tooltip+"' onclick='return false'> <b>"+name+":</b> </a>";
	else
		htmldata += "<b>"+name+":</b> ";
		
	htmldata+= "</td>   ";
	var alen = arr.length;
	
	var images_flag = document.getElementById('images_flag');
	for ( var i=0, len=alen; i<len; ++i ){
		var iu = allCardsArray[arr[i].name].imageURL;
		if (withImages && images_flag.checked) {
			htmldata += "<td><div id='card_cell'>";
		}
		else {
			htmldata += "<td><div>";
		}
		htmldata += card2html(arr[i], phase, markCards, withImages)+" ";
		htmldata += "</div></td>";
	}
	if (alen == 0) {
		if (withImages && images_flag.checked) {
			htmldata += "<td><div id='card_cell'></div></td>";
		}
		else {
			htmldata += "<td><div></div></td>";
		}
		
	}
	htmldata+="</tr><table>";
	
	return htmldata;
}

function card2htmlExtended(cur_card, phase, resources, start_tabs, min_tabs, withImages) {
	var my_coins = resources.coins;
	var my_potions = resources.potions;
	
	htmldata = "";
	for ( var i=start_tabs; i<min_tabs; ++i ){
		htmldata += "<td></td>";
	}
	if (phase == "Payment" || phase == "Buy") {
		if (cur_card.price.potions <= my_potions && cur_card.price.coins <= my_coins) {
			htmldata += "<td>"+card2html(cur_card, phase, "Kingdom_buy_mark", withImages);
		}
		else
			htmldata += "<td>"+card2html(cur_card, phase, "Kingdom_buy", withImages);
	}
	else
		htmldata += "<td>"+card2html(cur_card, phase, "Kingdom_always", withImages);
	if (cur_card.price.potions < 100) {	
		for (potions=0; potions < cur_card.price.potions; potions += 1) {
			htmldata += "&otimes;";
		}
		if (cur_card.price.potions > 0)
			htmldata += " ";
	}
	htmldata += "<font size='1'>"+cur_card.quantity+" </font></td>";
	
	return htmldata;
}

function kingdomCards2html(name, arr, resources, phase, withImages) {
	
	var htmldata = "<b>"+name+":</b> ";
	var alen = arr.length;
	
	var prices = new Array();
	var cur_price_arr = new Array();
	for ( var i=0, len=alen; i<len; ++i ){
		var card = allCardsArray[arr[i].name];
		card.price = arr[i].price;
		card['quantity'] = arr[i].quantity;
		
		cur_price = card.price.coins
		if (!(cur_price in prices)) {
			prices[cur_price] = new Array();
		}
		cur_price_arr = prices[cur_price];
		cur_price_arr.push(card);
		
	}
	
	var victory_pos = 0;
	var treasure_pos = 0;
	var kingdom_pos = 0;
	
	for(var key in prices){
		var cur_prices = prices[key];
		var cur_treasure_pos = victory_pos;
		for (i in cur_prices) {
			cur_card = cur_prices[i];
			if (!cur_card.isKingdom && (cur_card.isVictory || cur_card.isCurse || cur_card.isRuin)) {
				cur_treasure_pos += 1;
			}
			
			if (cur_treasure_pos > treasure_pos)
				treasure_pos = cur_treasure_pos;
		}
	}
	
	treasure_pos += 1
	
	for(var key in prices){
		var cur_prices = prices[key];
		var cur_kingdom_pos = treasure_pos;
		for (i in cur_prices) {	
			cur_card = cur_prices[i];
			if (!cur_card.isKingdom && cur_card.isTreasure) {	
				cur_kingdom_pos += 1;
			} 
			if (cur_kingdom_pos > kingdom_pos)
				kingdom_pos = cur_kingdom_pos;
		}
	}
	
	kingdom_pos += 1
		
	
	htmldata += "<table>";
	for(var key in prices){
		htmldata += "<tr>";
		if (key < 1000)
			htmldata += "<td><b>"+key+"$:</b></td><td/><td/><td/><td/>";
		else
			htmldata += "<td><b>&infin;$:</b></td><td/><td/><td/><td/>";
		
		var cur_prices = prices[key];
		var cur_prices_len = 0;
		
		for ( var j=cur_prices_len; j<victory_pos; ++j ){
			htmldata += "<td>&nbsp;&nbsp;&nbsp;</td>";
			
		}
		cur_prices_len = victory_pos;
		for (i in cur_prices) {
			cur_card = cur_prices[i];
			if (!cur_card.isKingdom && (cur_card.isVictory || cur_card.isCurse || cur_card.isRuin)) {
				htmldata += card2htmlExtended(cur_card, phase, resources, cur_prices_len, victory_pos, withImages)
				cur_prices_len += 1;
			}
		}
		
		for ( var j=cur_prices_len; j<treasure_pos; ++j ){
			htmldata += "<td>&nbsp;&nbsp;&nbsp;</td>";
		}
		cur_prices_len = treasure_pos;
		for (i in cur_prices) {
			cur_card = cur_prices[i];
			if (!cur_card.isKingdom && cur_card.isTreasure) {	
				htmldata += card2htmlExtended(cur_card, phase, resources, cur_prices_len, treasure_pos, withImages)
				cur_prices_len += 1;
			}	
		}
		
		for (var j=cur_prices_len; j<kingdom_pos; ++j ){
			htmldata += "<td>&nbsp;&nbsp;&nbsp;</td>";
		}
		cur_prices_len = kingdom_pos;
		for (i in cur_prices) {
			cur_card = cur_prices[i];
			if (cur_card.isKingdom) {
				htmldata += card2htmlExtended(cur_card, phase, resources, cur_prices_len, kingdom_pos, withImages)
				cur_prices_len += 1;
			}
		}
		
		
		htmldata+="</tr>"
	}
	
	htmldata+="</table><br />"
	return htmldata;
}

function getCardClass(card) {

	var cardClass = "";
	if (card.isRuin) {
		cardClass = "card_ruin";
	}
	else if (card.isDuration) {
		cardClass = "card_duration";
	}
	else if (card.isReaction && card.isTreasure) {
		cardClass = "card_reaction_treasure";
	}
	else if (card.isReaction && card.isVictory) {
		cardClass = "card_reaction_victory";
	}
	else if (card.isReaction) {
		cardClass = "card_reaction";
	}
	else if (card.isAction && card.isTreasure) {
		cardClass = "card_action_treasure";
	}
	else if (card.isAction && card.isVictory) {
		cardClass = "card_action_victory";
	}
	else if (card.isTreasure && card.isVictory) {
		cardClass = "card_treasure_victory";
	}
	else if (card.isAction) {
		cardClass = "card_action";
	}
	else if (card.isTreasure) {
		cardClass = "card_treasure";
	}
	else if (card.isVictory) {
		cardClass = "card_victory";
	}
	else if (card.isCurse) {
		cardClass = "card_curse";
	}
	return cardClass;
}

function card2simpleHtmlWithParams(name, d_name) {
	var card = allCardsArray[name];
	
	if (!card)
		return
	
	var cardClass = getCardClass(card);
	
 	// Does tool tip exists
	var hasToolTipClass = "";
	if(card.tooltip != "")
		hasToolTipClass = "hastooltip";

	// Create cards HTML
	
	var htmldata = "";
	htmldata = "<span class='simpleHtmlCard " + hasToolTipClass+ " " + cardClass + "'>" + d_name + "</span>";
	
	// Add description if exist
	if(card.tooltip != "") {
		htmldata += "<div class='tooltip'>" + card.tooltip + "</div>";
	}
	
	return htmldata;
}

function option2simpleHtmlWithParams(d_name) {
	var htmldata = "<span class='simpleHtmlCard option_class'>" + d_name + "</span>";
	return htmldata;
}

function card2html(card, phase, markCards, withImages) {
	var card = allCardsArray[card.name];
	htmldata = "";

	// If description exist add the tool tip class 
	var hasToolTipClass = ""
	if(card.tooltip != "")
		hasToolTipClass = "hastooltip";
	
	var href_start  = "<a href='#' class='"+hasToolTipClass+"' onclick='return false'>";
	var bold = ""
	var bolde = ""
	
	if (phase == "Action") {
		href_start = "<a href='javascript:void(0)' class='"+hasToolTipClass+"' onclick=\"playAction('"+card.name+"');\">";
	}
	if (phase == "Payment" || phase == "BlackMarketPayment" || phase == "DigitalStorePayment") {
		href_start = "<a href='javascript:void(0)' class='"+hasToolTipClass+"' onclick=\"playPayment('"+card.name+"');\">";
	}
	
	if (phase == "Buy" && markCards == "Kingdom_buy") {
		href_start = "<a  href='javascript:void(0)' class='"+hasToolTipClass+"' onclick=\"playBuy('"+card.name+"');\">"
	}
	
	if (phase == "Buy" && markCards == "Kingdom_buy_mark") {
		href_start = "<a  href='javascript:void(0)' class='"+hasToolTipClass+"' onclick=\"playBuy('"+card.name+"');\">"
		bold = "<b>";
		bolde = "</b>"
	}
	
	var through = ""
	if (markCards == "Kingdom_buy" || markCards == "Kingdom_always" || markCards == "Kingdom_buy_mark") {
		if (cur_card.quantity == 0) {
			through = "style='text-decoration:line-through;'";
			}
	}
	
	
	if (card.isAction && phase == "Action" && markCards == "Hand") {
		bold = "<b>";
		bolde = "</b>"
	}
	if (card.isTreasure && (phase == "Payment" || phase == "BlackMarketPayment" || phase == "DigitalStorePayment") && markCards == "Hand") {
		bold = "<b>";
		bolde = "</b>"
	}
	

	// Closes the href	
	var cardClass = getCardClass(card);
	
	htmldata += href_start;
	var images_flag = document.getElementById('images_flag');
	if (withImages && images_flag.checked) {
		var imageURL = card.imageURL
		htmldata += "<img src="+imageURL+" width='45' height='45'>";
		htmldata += "<br>"
	}
	htmldata += "<span class='"+cardClass+"' "+through+">"+bold+""+card.name+""+bolde+"</span> </a>";
	
	// Add description if exist
	if(card.tooltip != "") {
		htmldata += "<div class='tooltip'>" + card.tooltip + "</div>";
	}
	
	return htmldata;
	
}

function displayBeautifulString (title, cur_line) {
		paramHtmldata = ""
		temp_line = cur_line.line;
		for (var j=0; j < cur_line.params.length; j++) {
			
			var cur_param = cur_line.params[j]
			if (cur_param.length < 2)
				continue;
			var name = cur_param['name'];
			var d_name = cur_param['d_name'];
			paramHtmldata = card2simpleHtmlWithParams(name, d_name)
			temp_line = temp_line.replace(/\[!\]/, paramHtmldata, 1);
		}
			
		return "<b>"+title+"</b>: "+temp_line;
				
	}

function AlertMe() {

	document.getElementById("sec_sound").innerHTML="<embed src='sounds/s1.mp3' hidden='true' autostart='true' loop='false' />";
 
    var oldTitle = document.title;
    var msg = "Alarm! Alarm!";
    var timeoutId = setInterval(function() {
        document.title = document.title == msg ? ' Dominion' : msg;
    }, 750);
    window.onmousemove = function() {
        clearInterval(timeoutId);
        document.title = oldTitle;
        window.onmousemove = null;
    };
}

function ChatAlertMe() {

	document.getElementById("sec_sound").innerHTML="<embed src='sounds/s2.mp3' hidden='true' autostart='true' loop='false' />";
 
}









